package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiDuUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.models.auth.In;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Zonghe Wang
 * @Date: 2025/1/23 16:32
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiDuUtil baiDuUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) throws Exception{
        // 处理各种业务异常（地址簿为空、购物车为空）
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        String userAddress = address.getProvinceName()+address.getCityName()+address.getDistrictName()+address.getDetail();

        // 判断距离是否小于5公里
        Double distance;
//        String shopLocation = baiDuUtil.requestGetLocation(shopAddress);
//        String userLocation = baiDuUtil.requestGetLocation(userAddress);
//        distance = Double.valueOf(baiDuUtil.requestGetDistance(shopLocation, userLocation));
        try {
            String shopLocation = baiDuUtil.requestGetLocation(shopAddress);
            String userLocation = baiDuUtil.requestGetLocation(userAddress);
            distance = Double.valueOf(baiDuUtil.requestGetDistance(shopLocation, userLocation));
        } catch (Exception e) {
            throw new OrderBusinessException("超出配送范围，不能配送");
        }
        if(distance > 10000) { // 超过10公里，不能配送
            throw new OrderBusinessException("超出配送范围，不能配送");
        }


        // 查询购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.select(shoppingCart);
        if(shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setAddress(userAddress);

        orderMapper.insert(orders);
        // 订单明细表插入一或多条数据
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
        }
        orderDetailMapper.insertBatch(list);
        // 清空购物车数据
        shoppingCartMapper.delete(shoppingCart);

        // 封装VO
        OrderSubmitVO vo = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();
        return vo;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        /*// 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


        // 通过websocket向客户端浏览器推送信息
        Map map = new HashMap();
        map.put("type",1);// 1表示来单提醒 2表示用户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号是："+ordersDB.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);


        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


    }

    @Override
    public PageResult getOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Orders order = new Orders();
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(ordersPageQueryDTO.getStatus());
        Page<Orders> page = orderMapper.select(order);

        if (page != null && !page.isEmpty()) {
            List<OrderVO> list = new ArrayList<>();
            for (Orders o : page) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(o, orderVO);
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(o.getId());
                orderVO.setOrderDetailList(orderDetailMapper.select(orderDetail));
                list.add(orderVO);
            }
            return new PageResult(page.getTotal(), list);
        }
        return new PageResult(0, null);
    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders order = orderMapper.selectById(id);
        String phone = order.getPhone();
        String newPhone = phone.substring(0, 3)+"****"+phone.substring(7);
        order.setPhone(newPhone);
        String consignee = order.getConsignee();
        StringBuilder newConsignee = new StringBuilder(consignee.substring(0, 1));
        for(int i = 0; i < consignee.length()-1; ++i) {
            newConsignee.append("*");
        }
        order.setConsignee(newConsignee.toString());

        BeanUtils.copyProperties(order, orderVO);

        OrderDetail orderDetail = OrderDetail.builder()
                .orderId(id)
                .build();
        List<OrderDetail> orderDetails = orderDetailMapper.select(orderDetail);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    @Override
    public void cancel(Long id) {
        // 更改订单状态、取消原因（orders表）
        Orders orderDB = orderMapper.selectById(id);

        Integer status = orderDB.getStatus();
        Orders order = new Orders();
        if (status.equals(Orders.TO_BE_CONFIRMED)) {
            try {
                weChatPayUtil.refund(orderDB.getNumber(), orderDB.getNumber(), orderDB.getAmount(), orderDB.getAmount());
            } catch (Exception e) {
                throw new OrderBusinessException("退款失败");
            }
            order.setPayStatus(Orders.REFUND);
        } else if (status > 2) { //需要打电话
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setId(id);
        order.setCancelTime(LocalDateTime.now());
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        orderMapper.update(order);
    }

    @Override
    public void repetition(Long id) {
        // 查询订单信息
        OrderDetail orderDetail = OrderDetail.builder()
                .orderId(id)
                .build();
        List<OrderDetail> orderDetails = orderDetailMapper.select(orderDetail);
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail oD : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(oD, shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCarts.add(shoppingCart);
        }
        // 加入购物车表中
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    @Override
    public PageResult selectByCondition(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.selectPageDTO(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        for(Orders o : page) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(o, orderVO);
            Long id = o.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
            String dishes = "";
            for (OrderDetail orderDetail : orderDetails) {
                dishes += orderDetail.getName()+"*"+orderDetail.getNumber()+"; ";
            }
            orderVO.setOrderDishes(dishes);
            list.add(orderVO);
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.selectByStatus(Orders.CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.selectByStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.selectByStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders order = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(order);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        Integer payStatus = orders.getPayStatus();
        if(orders == null || orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException("不允许退款");
        }

        Orders order = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();


        if(payStatus == Orders.PAID) {
            // 退款
            /*try {
                weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), orders.getAmount(), orders.getAmount());
            } catch (Exception e) {
                throw new OrderBusinessException("退款失败");
            }*/
            order.setPayStatus(Orders.REFUND);
        }

        orderMapper.update(order);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        if(orders == null) {
            throw new OrderBusinessException("取消失败");
        }
        Integer payStatus = orders.getPayStatus();
        Orders order = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        if(payStatus == Orders.PAID) {
            // 退款
            /*try {
                weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), orders.getAmount(), orders.getAmount());
            } catch (Exception e) {
                throw new OrderBusinessException("退款失败");
            }*/
            order.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(order);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.selectById(id);
        if(orders == null || orders.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException("派送失败");
        }

        Orders order = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();

        orderMapper.update(order);
    }

    @Override
    public void comolete(Long id) {
        Orders orders = orderMapper.selectById(id);
        if(orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders order = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        orderMapper.update(order);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.selectById(id);
        if(orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type", 2); // 1来单提醒 2客户催单
        map.put("orderId", id);
        map.put("content","订单号为："+orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }
}
